<template>
	<div class="uni-file-picker__container" id="uni-file-picker__container_form">
		<div class="file-picker__box" v-for="(item,index) in filesList" :key="index" :style="boxStyle">
			<div class="file-picker__box-content" :style="borderStyle">
				
				<el-image v-if="isImage(item)" class="file-image" fit = "contain" :src="item.url"  @click="preview(item,index)"/>
				<el-image v-else class="file-image" :src="defaultIcon"  fit = "contain" @click="download(item)"/>
				
				<div v-if="delIcon && !readonly" class="icon-del-box" @click="delFile(index)">
					<div class="icon-del"></div>
					<div class="icon-del rotate"></div>
				</div>
				
				<div v-if="(item.progress && item.progress !== 100) ||item.progress===0 " class="file-picker__progress">
					<el-progress class="file-picker__progress-item" :percent="item.progress === -1?0:item.progress" stroke-width="4"
					 :backgroundColor="item.errMsg?'#ff5a5f':'#EBEBEB'" />
				</div>
				<div v-if="item.errMsg" class="file-picker__mask" @click="uploadFiles(item,index)">
					点击重试
				</div>
			</div>
			
			<div class="file-name">{{item.name}}</div>
		</div>
		
		
		<input  ref="input" type="file" style="display:none" @change="handleChange"/>
		
		<div v-if="filesList.length < limit && !readonly" class="file-picker__box" :style="boxStyle">
			<div class="file-picker__box-content is-add" :style="borderStyle" @click="choose">
				<slot>
					<div class="icon-add">
						<img src="@/assets/svg/u207.svg" style="width:32px;height:32px"/>
					</div>					
				</slot>
			</div>
		</div>
	</div>
</template>

<script>
	
	import file_img from "@/assets/images/file.png"
	
	export default {
		name: "uploadImage",
		emits:['http-request','before-remove'],
		props: {
			filesList: {
				type: Array,
				default () {
					return []
				}
			},
			disabled:{
				type: Boolean,
				default: false
			},
			disablePreview: {
				type: Boolean,
				default: false
			},
			data: {
				type: Object
			},
			field: {
				type: String,
				default:''
			},
			accept:{
				type: String,
				default: ""
			},
			limit: {
				type: [Number, String],
				default: 9
			},
			imageStyles: {
				type: Object,
				default () {
					return {
						width: 'auto',
						height: 'auto',
						border: {}
					}
				}
			},
			delIcon: {
				type: Boolean,
				default: true
			},
			readonly:{
				type:Boolean,
				default:false
			},
			httpRequest:{
				type: Object
			},
			beforeRemove:{
				type: Object
			},
			beforeUpload:{
				type: Object
			},
		},
		components:{
		},
		computed: {
			styles() {
				let styles = {
					width: 'auto',
					height: 'auto',
					border: {}
				}
				return Object.assign(styles, this.imageStyles)
			},
			boxStyle() {
				const {
					width = 'auto',
					height = 'auto'
				} = this.styles
				let obj = {}
				if (height === 'auto') {
					if (width !== 'auto') {
						obj.height = this.value2px(width)
						obj['padding-top'] = 0
					} else {
						obj.height = 0
					}
				} else {
					obj.height = this.value2px(height)
					obj['padding-top'] = 0
				}

				if (width === 'auto') {
					if (height !== 'auto') {
						obj.width = this.value2px(height)
					} else {
						obj.width = '25%'
					}
				} else {
					obj.width = this.value2px(width)
				}

				let classles = ''
				for(let i in obj){
					classles+= `${i}:${obj[i]};`
				}
				return classles
			},
			borderStyle() {
				let {
					border
				} = this.styles
				let obj = {}
				const widthDefaultValue = 1
				const radiusDefaultValue = 3
				if (typeof border === 'boolean') {
					obj.border = border ? '1px #eee solid' : 'none'
				} else {
					let width = (border && border.width) || widthDefaultValue
					width = this.value2px(width)
					let radius = (border && border.radius) || radiusDefaultValue
					radius = this.value2px(radius)
					obj = {
						'border-width': width,
						'border-style': (border && border.style) || 'solid',
						'border-color': (border && border.color) || '#eee',
						'border-radius': radius
					}
				}
				let classles = ''
				for(let i in obj){
					classles+= `${i}:${obj[i]};`
				}
				return classles
			}
		},
		data(){
		   return{
			   showViewer: false,
			   index:2,
			   images_urls:[],
			   defaultIcon: file_img,
			   visible:true,
			   previewUrl:''
		   }
		},
		methods: {
			uploadFiles(files) {
				if (this.limit && this.filesList.length + files.length > this.limit) {
				    return;
				}
				let postFiles = Array.prototype.slice.call(files);
				if (postFiles.length === 0) { 
					return; 
				}
				postFiles.forEach(rawFile => {
					 // 手动、自动上传前都会触发
					 this.onStart(rawFile);
					 
					 let item={
					 	 id:rawFile.lastModified,
					 	 name: rawFile.name,
					 	 type: rawFile.type,
					 	 raw:true
					 }
					 
					 let flag=true;
					 if (this.beforeUpload){
						 flag= this.beforeUpload(item);
					 }
					 
					 if (!flag){
						 return;
					 }
					 					 
					 let reader=new FileReader();
				
					 reader.readAsDataURL(rawFile);
					 reader.onload=(e)=>{
						 
						 let file={
							 id: rawFile.lastModified,
							 file: rawFile,
							 name: rawFile.name,
							 type: rawFile.type
						 }
						 
						 item.url=e.target.result;
						 
						 this.filesList.push(item);
						 if (this.$props.data){
							 file.data=this.$props.data;
						 }
						 if (this.$props.field){
							 file.field=this.$props.field;
						 }
						 
						 if (this.httpRequest){
						 						 
						    this.httpRequest(file);
						 }
						 this.$emit("http-request", file);
					 }
					 
				});
			},
			choose() {
				if (this.accept){
					this.$refs.input.accept=this.accept;
				}
				this.$refs.input.value = null;
				this.$refs.input.click();
				
			},
			delFile(index) {
				let file=this.filesList[index];
				if (this.$props.data){
					file.data=this.$props.data;
				}
				if (this.$props.field){
				   file.field=this.$props.field;
				}
				if (this.beforeRemove){
					let flag=this.beforeRemove(file);
					if (flag || flag==undefined){
						this.filesList.splice(index, 1);
					}
				}else{
					this.$emit("before-remove", file);
					this.filesList.splice(index, 1);
				}
			},
			close(){
			   this.showViewer=false;
			},
			isImage(file){				
				let ext=file.name.split(".")[1];
				return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
			},
			onStart(e){
				
			},
			handleChange(e){
				const files = e.target.files;
				if (!files) return;
				this.uploadFiles(files);
			},
			download(img){
				const link = document.createElement('a');
				link.href = img.url;
				const fname = img.name;
				link.setAttribute('download', fname);
				link.setAttribute('target', "_blank");
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);	
			},
			preview(img, index) {
				
				this.$emit("preview", img.url);
				//this.images_urls=[];
				//this.images_urls.push(img.url);
				//this.index=0;
				//this.previewUrl=img.url;
				//this.showViewer=true;
							
				/* this.$nextTick(()=>{	
					let container=document.getElementById("uni-file-picker__container_form");
					let wrapper=container.querySelectorAll('.el-image-viewer__img')[0];
						
					let that = this;
					that.deg=0;
										
					let img=document.createElement("img");
					img.setAttribute("class","el-image-viewer__img");
					img.setAttribute("style", wrapper.getAttribute("style"));
					img.setAttribute("src", wrapper.getAttribute("src"));
					img.setAttribute("zt","1");
					
					img.onclick=function(){
						that.showViewer=false;
					}
					
													
					let parent=wrapper.parentElement;
					parent.appendChild(img);
					
					parent.removeChild(wrapper);
					
					let panel=container.querySelectorAll('.el-image-viewer__actions__inner')[0];
					for (let i=0;i<panel.children.length;i++){
						let btn=panel.children[i];
						if (i==0){
							btn.onclick=function(){
								let h=img.height;
								let w=img.width;
								h=h*0.9;
								w=w*0.9;
								if (h>60){
								  img.width=w;
								  img.height=h;
								}
							}
						}else if (i==1){
							btn.onclick=function(){
								let h=img.height;
								let w=img.width;
								h=h*1.1;
								w=w*1.1;
								let sw=parent.clientWidth;
								let sl=parent.clientHeight;
																			
								if (h<sl && w<sw){
								  img.width=w;
								  img.height=h;
								}
							}
						}else if (i==3){
							btn.onclick=function(){
								let h=img.height;
								let w=img.width;
								
								let sw=parent.clientWidth;
								let sl=parent.clientHeight;
										
								while(true){
									if (h*1.1>sl || w*1.1>sw){
									  break;
									}else{
										h=h*1.1;
										w=w*1.1;
									}	
								}		
								img.width=w;
								img.height=h;							
								
							}
						}else if (i==5){
							btn.onclick=function(){
								that.deg=that.deg-90;
								if (that.deg==0){
									that.deg=360;
								}
								img.style.transform='scale(1) rotate('+that.deg+'deg) translate(0px, 0px)';
							}
						}else if (i==6){
							btn.onclick=function(){
								that.deg=that.deg+90;
								if (that.deg==360){
									that.deg=0;
								}
								img.style.transform='scale(1) rotate('+that.deg+'deg) translate(0px, 0px)';
							}
						}
					} 
					
				}) */
				
			},
			value2px(value) {
				if (typeof value === 'number') {
					value += 'px'
				} else {
					if (value.indexOf('%') === -1) {
						value = value.indexOf('px') !== -1 ? value : value + 'px'
					}
				}
				return value
			}
		}
	}
</script>

<style lang="scss">
	.uni-file-picker__container {
		/* #ifndef APP-NVUE */
		display: flex;
		box-sizing: border-box;
		/* #endif */
		flex-wrap: wrap;
		
		padding:5px;
		border:1px solid #c2c2c2;
		border-radius: 5px;
	}

	.file-picker__box {
		position: relative;
		// flex: 0 0 33.3%;
		width: 33.3%;
		height: 0;
		padding-top: 33.33%;
		/* #ifndef APP-NVUE */
		box-sizing: border-box;
		/* #endif */
		
		
		
		.file-name{
			width: 100%;
			text-align: center;
			text-overflow:ellipsis; 
			white-space:nowrap; 
			overflow:hidden; 
			
			color: black;
			position: absolute;
			bottom: -20px;
		}
	}

	.file-picker__box-content {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		margin: 5px;
		border: 1px #eee solid;
		border-radius: 5px;
		overflow: hidden;
	}

	.file-picker__progress {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		/* border: 1px red solid; */
		z-index: 2;
	}

	.file-picker__progress-item {
		width: 100%;
	}

	.file-picker__mask {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
		position: absolute;
		right: 0;
		top: 0;
		bottom: 0;
		left: 0;
		color: #fff;
		font-size: 12px;
		background-color: rgba(0, 0, 0, 0.4);
	}

	.file-image {
		width: 100%;
		height: 100%;
		cursor: pointer;
	}

	.is-add {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		align-items: center;
		justify-content: center;
	}

	.icon-add {
		//width: 50px;
		//height: 5px;
		//background-color: #f1f1f1;
		border-radius: 5px;
		cursor: pointer;
	}

	.rotate {
		position: absolute;
		transform: rotate(90deg);
	}

	.icon-del-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		align-items: center;
		justify-content: center;
		position: absolute;
		top: 3px;
		right: 3px;
		height: 26px;
		width: 26px;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 2;
		transform: rotate(-45deg);
	}

	.icon-del {
		width: 15px;
		height: 2px;
		background-color: #fff;
		border-radius: 2px;
	}
</style>
